﻿using Admin.Application.DynamicApi.System.Role.Dto;
using Admin.Database.Enums;
using Admin.Database.Model;
using Framework.DI;
using Framework.SqlSugar.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Application.DynamicApi.System.Role
{
	/// <summary>
	/// 系统角色机构服务
	/// </summary>
	public class SysRoleOrgService: ISelfTransientAutoInject
	{
		private readonly SqlSugarRepository<SysRoleOrg> _sysRoleOrgRep;

		public SysRoleOrgService(SqlSugarRepository<SysRoleOrg> sysRoleOrgRep)
		{
			_sysRoleOrgRep = sysRoleOrgRep;
		}

		/// <summary>
		/// 授权角色机构
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task GrantRoleOrg(RoleOrgInput input)
		{
			await _sysRoleOrgRep.DeleteAsync(u => u.RoleId == input.Id);
			if (input.DataScope == (int)DataScopeEnum.Define)
			{
				var roleOrgList = input.OrgIdList.Select(u => new SysRoleOrg
				{
					RoleId = input.Id,
					OrgId = u
				}).ToList();
				await _sysRoleOrgRep.InsertRangeAsync(roleOrgList);
			}
		}

		/// <summary>
		/// 根据角色Id集合获取角色机构Id集合
		/// </summary>
		/// <param name="roleIdList"></param>
		/// <returns></returns>
		public async Task<List<long>> GetRoleOrgIdList(List<long> roleIdList)
		{
			if (roleIdList?.Count > 0)
			{
				return await _sysRoleOrgRep.AsQueryable()
					.Where(u => roleIdList.Contains(u.RoleId))
					.Select(u => u.OrgId).ToListAsync();
			}
			else return new List<long>();
		}

		/// <summary>
		/// 根据机构Id集合删除角色机构
		/// </summary>
		/// <param name="orgIdList"></param>
		/// <returns></returns>
		public async Task DeleteRoleOrgByOrgIdList(List<long> orgIdList)
		{
			await _sysRoleOrgRep.DeleteAsync(u => orgIdList.Contains(u.OrgId));
		}

		/// <summary>
		/// 根据角色Id删除角色机构
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public async Task DeleteRoleOrgByRoleId(long roleId)
		{
			await _sysRoleOrgRep.DeleteAsync(u => u.RoleId == roleId);
		}
	}
}
